#include <stdio.h>
#include "common.h"

int SequentialSearch(int *buff, int buff_len, int data)
{
	int i = 0;

	if (buff == NULL || buff_len <= 0)
	{
		return PARAMETER_ERROR;
	}

	while (i < buff_len)
	{
		if (buff[i++] == data)
		{
			return (i - 1);
		}
	}

	return UNFOUND_ERROR;
}

static int do_BinarySearch(int *buff, int low, int high, int data)
{
	int mid = 0;

	if (low == high && buff[mid] != data)
	{
		return UNFOUND_ERROR;
	}

	mid = low + ((high - low) >> 1);

	if (buff[mid] == data)
	{
		return mid;
	}
	else if (buff[mid] > data)
	{
		return do_BinarySearch(buff, low, mid, data);
	}
	return do_BinarySearch(buff, mid + 1, high, data);
}

int BinarySearch(int *buff, int buff_len, int data)
{
	if (buff == NULL || buff_len <= 0)
	{
		return PARAMETER_ERROR;
	}

	return do_BinarySearch(buff, 0, buff_len, data);
}
